//
//  NetWork.swift
//  NewApp
//
//  Created by weijieMac on 2019/4/3.
//  Copyright © 2019 Mac. All rights reserved.
//

import Foundation
import SVProgressHUD

struct Response : Codable {
    let error : Int
    let msg : String
    let mbstr : Mbstr
    
    struct Mbstr : Codable {
        let str : String
        let time : Int
    }
}

var isFirstLaunch = true

//登录
func net_login(account:String,password:String,savePassword:Bool = false, success:(()->())? = nil) {
    networkManager.request(.login(password:(password).base64String())) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "0" {
                UserInfoManager.shared().saveLoginInfo(account: account, password: password, savePassword: savePassword)
                SVProgressHUD.showSuccess(withStatus: "Login Success")
                if success != nil {
                    success!()
                }
            }else {
                SVProgressHUD.showError(withStatus: "Login failure")
            }
        case .failure(let error):
            print("______\(error)")
        }
    }
}

//登出
func net_logout() {
    networkManager.request(.logout()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                UserInfoManager.shared().isLogin = false
//                UserInfoManager.shared().saveLoginInfo(account: UserInfoManager.shared().account, password: "", savePassword: false)
                SVProgressHUD.showSuccess(withStatus: "Logout")
            }
        case .failure(let error):
            print("______\(error)")
        }
    }
}

//重启设备
func net_restartDevice() {
    networkManager.request(.restartDevice()) { (result) in
        switch result{
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                UserInfoManager.shared().isConnected = false
            }
        case .failure(_):
            print("=====")
        }
    }
}

//恢复出厂设置
func net_restoreFactory() {
    networkManager.request(.restoreFactory()) { (result) in
        switch result{
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                UserInfoManager.shared().isConnected = false
            }
        case .failure(_):
            print("=====")
        }
    }
}


//设置消息为未读消息数
func net_setMessageReaded(msg_id:String) {
    networkManager.request(.setMessageReaded(msg_id: msg_id)) { (result) in
        switch result{
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                
            }
        case .failure(_):
            print("=====")
        }
    }
}


//staus 页面获取设备信息
func net_getDeviceInfo(handle:@escaping ((StatusVCDeviceInfoModel?)->())) {
    
//    if !UserInfoManager.shared().isConnected {
//        
//        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
//            net_getDeviceInfo(handle:handle)
//        })
//        
//        return;
//    }
    
    
    networkManager.request(.getDeviceInfo()) { (result) in
        switch result{
        case .success(let resp):
            let data = try? JSONDecoder().decode(StatusVCDeviceInfoModel.self, from: resp.data)
            UserInfoManager.shared().isLogin = data?.loginfo == "ok"
            
            UserInfoManager.shared().pin_status = data?.pin_status ?? "0"
            if data?.loginfo != "ok" && UserInfoManager.shared().password != "" {
                if !isFirstLaunch {
                    isFirstLaunch = false
                    net_login(account: UserInfoManager.shared().account,
                              password: UserInfoManager.shared().password,
                              savePassword: true)
                }
            }
            handle(data)
        case .failure(_):
            
            
            handle(nil)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            net_getDeviceInfo(handle:handle)
        })
    }
}


//检测是否登录
func net_setMessageReaded(handle:@escaping ((Bool)->())) {
    net_getDeviceInfo { (model) in
        var isLogin = false
        if model?.loginfo == "ok" {
            isLogin = true
        }
        handle(isLogin)
    }
}

//检测是否登录
func net_checkLogin(handle:@escaping ((Bool)->())) {
    net_getDeviceInfo { (model) in
        var isLogin = false
        if model?.loginfo == "ok" {
            isLogin = true
        }
        handle(isLogin)
    }
}

//连接到设备
func net_connect() {
    
    
    networkManager.request(.connect()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            let isConnected = data?.result == "success"
            if !isConnected {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                    net_connect()
                })
            }
        case .failure(let error):
            DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                net_connect()
            })
        }
    }
}

//获取连接的手机信息
func net_getDevices(handle:@escaping ((DevicesModel?)->())){
    networkManager.request(.getDevices()) { (result) in
        switch result {
        case .success(let resp):
        
            let data = try? JSONDecoder().decode(DevicesModel.self, from: resp.data)
            handle(data)
            
        case .failure(_):
            handle(nil)
        }
    }
}

//获取设置页面device info
func net_getDeviceInfoList(handle:@escaping ((DeviceInfoVCInfo?)->())) {
    networkManager.request(.getDeviceInfoList()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(DeviceInfoVCInfo.self, from: resp.data)
            handle(data)
        case .failure(_):
            handle(nil)
        }
    }
}
//获取wifi休眠shijian
func net_getDeviceWifiTime(handle:@escaping ((DeviceInfoVCInfo?)->())) {
    networkManager.request(.getwifiTime()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(DeviceInfoVCInfo.self, from: resp.data)
            handle(data)
        case .failure(_):
            handle(nil)
        }
    }
}

//net setting get network mode
func net_getNetMode(handle:@escaping ((String)->())) {
    networkManager.request(.getNetMode()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(NetModeModel.self, from: resp.data)
            if data != nil {
                if data!.net_select != nil {
                    var result = ""
                    if data!.net_select!.caseInsensitiveCompare("NETWORK_auto") == .orderedSame {
                        result = "Auto"
                    }
                    if data!.net_select!.caseInsensitiveCompare("Only_LTE") == .orderedSame {
                        result = "4G"
                    }
                    if data!.net_select!.caseInsensitiveCompare("Only_WCDMA") == .orderedSame {
                        result = "3G"
                    }
                    if data!.net_select!.caseInsensitiveCompare("Only_GSM") == .orderedSame {
                        result = "2G"
                    }
                    handle(result)
                }
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle("")
        }
    }
}

//net setting set network mode
func net_setNetMode(mode:Int,handle:@escaping ((Bool)->())) {
    
    
    networkManager.request(.setDisconnet()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                
                networkManager.request(.setNetMode(mode:mode)) { (result) in
                    switch result {
                    case .success(let resp):
                        let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
                        if data?.result == "success" {
                            SVProgressHUD.showSuccess(withStatus: "Setup success")
                            handle(true)
                        }else {
                            SVProgressHUD.showError(withStatus: "Setup failure")
                            handle(false)
                        }
                    case .failure(_):
                        SVProgressHUD.showError(withStatus: "Setup failure")
                        handle(false)
                    }
                }
               
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
    
 
}


//网络setting页面设置网络
func net_setNet(request:NetworkManager,handle:@escaping ((Bool)->())) {
    networkManager.request(request) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

//reset wifi sleep time
func net_setWifiReSetTime(time:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.setWifiReSetTime(time:time)) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

//SSID save INFO
func net_setSSID(ssid:String,broadcast:String,secureMode:String,pwd:String,max:String,cipher:String,shared:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.setSSID(ssid: ssid, broadcast: broadcast, secureMode: secureMode, pwd: pwd, max: max, cipher: cipher, shared: shared)) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

//set WPS
func net_setWPS(mode:String,pin:String?,ssid:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.setWPS(mode: mode, pin: pin, ssid: ssid)) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

//mac list
func net_getACLMode(handle:@escaping ((MacAddressListModel?)->())) {
    networkManager.request(.getACLMode()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(MacAddressListModel.self, from: resp.data)
            handle(data)
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(nil)
        }
    }
}

//set mac list
func net_setACLMode(aclmode:String,blackList:String,whiteList:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.setACLMode(aclmode: aclmode, blackList: blackList, whiteList: whiteList)) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

//reset account
func net_updateAccount(oldA:String,newA:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.updateAccount(newPassword:newA.base64String(),newAccount:oldA.base64String())) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

//reset password
func net_updatePassword(oldP:String,newP:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.updatePassword(newPassword:oldP.base64String(),newAccount:UserInfoManager.shared().account.base64String())) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

func net_setPinSwitch(status:Bool,code:String,handle:@escaping ((Bool)->())) {
    
    
    
    networkManager.request(.setDisconnet()) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                
                networkManager.request(.setPinSwitch(status: status, code: code)) { (result) in
                    switch result {
                    case .success(let resp):
                        let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
                        if data?.result == "success" {
                            SVProgressHUD.showSuccess(withStatus: "Setup success")
                            handle(true)
                        }else {
                            SVProgressHUD.showError(withStatus: "Setup failure")
                            handle(false)
                        }
                    case .failure(_):
                        SVProgressHUD.showError(withStatus: "Incorrect pin value")
                        handle(false)
                    }
                }
                
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
    
    
    
}

//se limitData
func net_setLimitData(limitSwitch:String, unit:String, size:String, percent:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.setLimitData(limitSwitch:limitSwitch, unit:unit, size:size, percent:percent)) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

//get sms
func net_getSMSList(handle:@escaping (([SMSListModel.Message]?)->())) {
    networkManager.request(.getSMSList()) { (result) in
        switch result {
        case .success(let resp):
            
            let data = try? JSONDecoder().decode(SMSListModel.self, from: resp.data)
            if data?.messages != nil && data!.messages!.count > 0 {
                handle(data!.messages!)
            }else {
                handle(nil)
            }
            break
        case .failure(_):
            handle(nil)
        }
    }
}

//delete sms
func net_deleteSMS(id:String,handle:@escaping ((Bool)->())) {
    networkManager.request(.deleteSMS(id:id)) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}

func net_getUSSDFlag(handle:@escaping ((String?)->())) {
    networkManager.request(.getUSSDFlag()) { (result) in
        switch result {
        case .success(let resp)://返回值 ussd_write_flag为空
            let data = try? JSONDecoder().decode(USSDModel.self, from: resp.data)
            if data != nil {
                handle(data!.ussd_write_flag)
            }else {
                handle(nil)
            }
            
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(nil)
        }
    }
}

func net_sendSMS(number:String,message:String,handle:@escaping ((Bool)->())) {

networkManager.request(.sendSMS(number:number,message:message.stringToUnicode())) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Send success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Send failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Send failure")
            handle(false)
        }
    }
}

func net_sendUSSD(number:String,handle:@escaping ((Bool)->())) {
    
    networkManager.request(.sendUSSD(number:number)) { (result) in
        switch result {
        case .success(let resp):
            let data = try? JSONDecoder().decode(LoginResult.self, from: resp.data)
            if data?.result == "success" {
                SVProgressHUD.showSuccess(withStatus: "Setup success")
                handle(true)
            }else {
                SVProgressHUD.showError(withStatus: "Setup failure")
                handle(false)
            }
        case .failure(_):
            SVProgressHUD.showError(withStatus: "Setup failure")
            handle(false)
        }
    }
}
